package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-07-11
 * Time: 8:49
 */
public class TCPEchoClient {
    private Socket socket = null;

    public TCPEchoClient(String serverIp,int port) throws IOException {
        //建立连接 这个操作就是让客户端和服务器建立连接
        //这里连接上了服务器的accept就会返回
        socket = new Socket(serverIp,port);
    }

    public void start() throws IOException {
            Scanner sc = new Scanner(System.in);
            try(InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream()) {
                PrintWriter printwriter = new PrintWriter(outputStream);
                Scanner scannerFromSocket = new Scanner(inputStream);
                while(true) {
                    //1.从键盘上读取用户输入的内容
                    System.out.print("-> ");
                    String request = sc.next();
                    //2.把读取的内容构造成请求，发送给服务器
                    //这里的发送有换行！！！进行发送操作
                    printwriter.println(request);
                    printwriter.flush();
                    //3.从服务器读取响应内容
                    String response =  scannerFromSocket.next();
                    //4.把响应结果显示到控制台
                    System.out.printf("req:%s;resp:%s\n",request,response);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    public static void main(String[] args) throws IOException {
        TCPEchoClient client = new TCPEchoClient("127.0.0.1",9090);
        client.start();
    }
}
